<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- 顶部导航 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<uni-icons type="left" size="20" color="#1890ff"></uni-icons>
				<text>返回</text>
			</view>
			<text class="title">订单结算</text>
		</view>
		<template v-if="products">
			<!-- 选择地址 -->
			<view class="address-section">
				<view class="address" @click="selectAddress">
					<view class="address-title">选择地址 </view>
					<uni-icons type="right" color="#999"></uni-icons>
				</view>
				<view class="address-item">
					<view class="name">{{ defaultAddress.name }}</view>
					<view class="phone">{{ defaultAddress.tel }}</view>
					<view class="default-tag" v-if="defaultAddress.isDefault">默认</view>
				</view>
				<view class="address-detail">{{ defaultAddress.addressDetail }}</view>
			</view>
			<!-- 订单信息 -->
			<view class="order-info">
				<view class="section-title">订单信息</view>
				<view v-for="(item, index) in products" :key="index" class="order-item">
					<image :src="image(item)" class="product-image" />
					<view class="product-info">
						<view class="product-name">{{ item.name }} <text class="product-spec" style="margin-left:30rpx;">{{
							item.rule }}</text> </view>
						<view class="product-spec"> {{ item.enname }}</view>
						<view class="price-tag">¥{{ item.price }}</view>
					</view>
					<view class="quantity">x{{ item.count }}</view>
				</view>
				<view class="total-info">
					<text>共计 {{ totalQuantity }} 件商品</text>
					<text class="total-price">订单金额：¥{{ totalPrice }}</text>
				</view>
			</view>
			<!-- 立即结算按钮 -->
			<button class="submit-btn" @click="handleSettlement">立即结算</button>
		</template>
		<template v-else>
			<uv-empty mode="order" class="center"></uv-empty>
		</template>
		<uv-popup ref="popup" mode="bottom" @change="change" duration="500">

			<view class="popup">

				<view class="select-address-title">
					<text>选择地址</text> <uv-icon size="20" name="close" @click="closePopUp"></uv-icon>
				</view>
				<uv-radio-group class="radio-container" shape="circle" v-model="selectedIndex" @change="onChange">
					<view v-for="(address, index) in allAddress" :key="index" class="address-container">
						<uv-radio :name="index" class="radio"></uv-radio>
						<view class="address-list" @click="selectedRadio(index)">
							<view class="address-item">
								<view class="name">{{ address.name }}</view>
								<view class="phone">{{ address.tel }}</view>
								<view class="default-tag" v-if="address.isDefault">默认</view>
							</view>
							<view class="address-detail">{{ address.addressDetail }}</view>
						</view>
					</view>
				</uv-radio-group>


				<button class="save-btn" @click="saveAddress">新增地址</button>


			</view>
		</uv-popup>
	</view>
</template>
<script setup>
import {
	commitShopcart,
	findAddress,
	pay
} from "@/api/index.js"
import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
import {
	ref,
	reactive,
	computed,
	onMounted
} from 'vue';
import {
	onLoad
} from "@dcloudio/uni-app"
const popup = ref(null)
const allAddress = ref([])

const selectedIndex = ref(0)


const defaultAddress = reactive({
	name: '',
	tel: '',
	isDefault: 0,
	addressDetail: ''
})
const products = JSON.parse(uni.getStorageSync('product'))

const sids = ref([])

const getSids = () => {


	products.forEach(product => {
		sids.value.push(product.sid)
	})

	console.log("sids:", sids.value)

	return sids.value
}



// const products = uni.getStorageSync('product')
console.log("products:", products)
onMounted(async () => {
	getSids()



	// 加载收货地址
	const res = await findAddress(uni.getStorageSync('coffee_token'))
	// console.log("收货地址:",res)
	if (res.code === 20000) {
		allAddress.value = res.result //全部地址
		console.log("allAddress:", allAddress.value)
		// const address = res.result.find(address => address.isDefault === 1)

		if (res.result.length > 0) {
			// 设置默认选中第一个
			selectedIndex.value = 0
			// 默认选择第一个地址
			defaultAddress.name = res.result[0].name
			defaultAddress.tel = res.result[0].tel
			defaultAddress.isDefault = res.result[0].isDefault
			defaultAddress.addressDetail = res.result[0].addressDetail
		}
	}
})
// 产品图片
const image = (item) => {
	return 'https://placehold.co/600' || item.small_img;
}
// 计算属性
const totalQuantity = computed(() => {
	return products.reduce((sum, item) => sum + item.count, 0)
});
const totalPrice = computed(() => {
	return products.reduce((sum, item) => sum + item.price * item.count, 0).toFixed(2)
});
// 立即结算逻辑
const handleSettlement = async () => {
	uni.showToast({
		title: '订单提交成功',
		icon: 'success'
	});
	// 实际开发中调用结算接口

	const res = await pay(uni.getStorageSync('coffee_token'),JSON.stringify(sids.value),defaultAddress.tel,defaultAddress.addressDetail, defaultAddress.name)
     console.log("结算接口",res)
	 // 结算成功
	  if(res.code === 60000){
		  uni.showToast({
		  	title:res.msg
		  })
	  }
	  // 结算之后将购物车清空
	  uni.setStorageSync('product',JSON.stringify([]))
	  
	 // 然后跳转到订单页面
	  uni.navigateTo({
	  	url:'/pages/orders/orders'
	  })


};
//选择地址
const selectAddress = () => {
	popup.value.open()
}
// 
const closePopUp = () => {
	popup.value.close()
}

const onChange = (name) => {
	console.log("onChange", name)
	selectedIndex.value = name



	// 更新默认地址信息
	const selectedAddress = allAddress.value[name];
	defaultAddress.name = selectedAddress.name;
	defaultAddress.tel = selectedAddress.tel;
	defaultAddress.isDefault = selectedAddress.isDefault;
	defaultAddress.addressDetail = selectedAddress.addressDetail;





	// 关闭弹窗
	popup.value.close();

}





//点击选择某个地址index
const selectedRadio = (index) => {

	selectedIndex.value = index



	// 更新默认地址信息
	const selectedAddress = allAddress.value[index];
	defaultAddress.name = selectedAddress.name;
	defaultAddress.tel = selectedAddress.tel;
	defaultAddress.isDefault = selectedAddress.isDefault;
	defaultAddress.addressDetail = selectedAddress.addressDetail;



	// 关闭弹窗
	popup.value.close();

}



const goBack = () => {
const pages = getCurrentPages();
	if (pages.length > 1) uni.navigateBack();
		else  uni.switchTab({ url: '/pages/index/index' });
}


const saveAddress = () => {
	uni.navigateTo({
		url: '/pages/address/add'
	})
};


</script>
<style scoped>
.container {
	padding: 0 20rpx 150rpx 20rpx;
	background-color: #eee;
	min-height: 100vh;
}

.header {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100rpx;
	border-bottom: 1rpx solid #eee;
}

.back-icon {
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	font-size: 28rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
}

.address-section {
	margin: 40rpx 0;
	background: white;
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	flex-wrap: nowrap;
	align-content: flex-start;
	justify-content: center;
	align-items: flex-start;
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
}

.address {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
	gap: 10rpx;
}

.address-title {
	font-size: 30rpx;
	/* margin-bottom: 20rpx; */
}

.address-item {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-bottom: 10rpx;
}

.name {
	font-size: 28rpx;
	font-weight: bold;
}

.phone {
	font-size: 24rpx;
	color: #666;
	margin-left: 20rpx;
}

.default-tag {
	background: #232773;
	color: white;
	padding: 4rpx 12rpx;
	border-radius: 30rpx;
	font-size: 20rpx;
	margin-left: 20rpx;
}

.address-detail {
	font-size: 24rpx;
	color: #666;
	margin-top: 10rpx;
}

.order-info {
	margin-top: 20rpx;
	background: white;
	padding: 20rpx;
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
}

.section-title {
	font-size: 28rpx;
	margin: 10rpx 0 20rpx 0;
}

.order-item {
	display: flex;
	align-content: center;
	justify-content: flex-start;
	gap: 30rpx;
	align-items: flex-end;
	margin-bottom: 20rpx;
	/* margin-top: 20rpx; */
}

.product-image {
	width: 150rpx;
	height: 150rpx;
	border-radius: 8rpx;
	/* margin-right: 20rpx; */
}

.product-info {
	width: calc(100vw - 400rpx);
	display: flex;
	flex-direction: column;
}

.product-name {
	font-size: 28rpx;
	margin-bottom: 10rpx;
}

.product-spec {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 10rpx;
	overflow: hidden;
	/* 隐藏超出容器的内容 */
	white-space: nowrap;
	/* 禁止文本换行，保持单行显示 */
}

.price-tag {
	color: red;
	font-weight: bold;
	font-size: 28rpx;
}

.quantity {
	font-size: 28rpx;
	color: #666;
	margin-left: auto;
}

.total-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 20rpx;
	border-top: 1px solid #eee;
	padding: 30rpx 10rpx;
}

.total-price {
	color: red;
	font-weight: bold;
	font-size: 28rpx;
}

.submit-btn {
	background: #232773;
	color: white;
	border-radius: 60rpx;
	padding: 10rpx 20rpx;
	font-size: 32rpx;
	margin-top: 50rpx;
}

.center {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	width: 160px;
	height: 160px;
}

.popup {
	padding: 30rpx;
}



.select-address-title {
	/* padding: 20rpx; */
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 50rpx;
}


.radio-container {
	/* padding: 20rpx; */

}


.address-container {
	/* padding: 10rpx; */
	display: flex;
	align-items: center;
	justify-content: flex-start;
	width: 100%;
	margin-bottom: 50rpx;
}

.radio {
	margin: 0 20rpx;
}


.uv-radio-group {
	flex: 0;

}


.save-btn {
	background: #232773;
	color: white;
	border-radius: 60rpx;
	padding: 10rpx 10rpx;
	font-size: 32rpx;
	margin-top: 10rpx;
}
</style>